<script lang="ts" setup name="LoginForm">
import { ref, watch, watchEffect } from 'vue';
import useStore from '@/store/index'
import Message from '@/components/message'
import { useRoute, useRouter } from 'vue-router';
import { useField, useForm } from 'vee-validate'
import { useIntervalFn } from '@vueuse/core'
import { useCountDown } from '@/utils/hooks'
import { accountRule, codeRule, isAgreeRule, mobileRule, passwordRule } from '@/utils/validate';
const route = useRoute()
const { count: time, start } = useCountDown()
const { user } = useStore()
const router = useRouter()
const activeName = ref<'mobile' | 'account'>('account')
// const changeflag = (flag: boolean) => {
//   console.log('最新的状态', flag);
// }
// 账户密码关联的数据
// const form = ref({
//   account: '',
//   password: '',
//   isAgree: false,
// })

// function fn() {
const { validate, resetForm } = useForm({
  // 初始化默认值
  initialValues: {
    account: 'cdshi0013',
    password: '123456',
    mobile: '13012345710',
    code: '123456',
    isAgree: true
  },
  validationSchema: { //添加每一项表单的规则
    account: accountRule,
    password: passwordRule,
    code: codeRule,
    mobile: mobileRule,
    isAgree: isAgreeRule
  }
})

//重置表单校验规则
watch(activeName, () => {
  resetForm()
})

//value输入框输入的内容和表单双向绑定 errormessage错误的提示信息
const { value: account, errorMessage: accountErrorMessage } = useField<string>('account')
const { value: password, errorMessage: passwordErrorMessage } = useField<string>('password')
const { value: isAgree, errorMessage: isAgreeErrorMessage } = useField<boolean>('isAgree')
const { value: mobile, errorMessage: mobileErrorMessage, validate: validateMobile } = useField<string>('mobile')
const { value: code, errorMessage: codeErrorMessage } = useField<string>('code')

// return {
//   account,
//   accountErrorMessage
// }
// }

// const {account,accountErrorMessage} = fn()
//点击登录按钮
const handleLogin = async () => {
  // console.log(validate);
  const result = await validate()
  // console.log(result);
  //校验不通过
  // if (!result.valid) return
  //发送请求
  if (activeName.value === 'account') {
    if (result.errors.account || result.errors.password || result.errors.isAgree) return
    // 1、发送请求
    await user.login({ account: account.value, password: password.value })
    // await user.login(form.value)
  } else {
    if (result.errors.mobile || result.errors.code || result.errors.isAgree) return
    await user.mobileLogin(mobile.value, code.value)
  }
  // 2、消息提示
  Message.success('登录成功')
  // 3、跳转首页
  // 先看地址栏中有没有要回跳的页面 有就回调出去
  if (route.query.redirectUrl) {
    router.push(route.query.redirectUrl as string)
  } else {
    router.push('/')
  }
}
const mobileref = ref<null | HTMLInputElement>(null)
//利用vueuse里的useIntervalFn来处理定时器功能
// const { pause, resume } = useIntervalFn(() => {
//   count.value--
//   if (count.value <= 0) pause()
// }, 1000, { immediate: false })
//获取验证码
const send = async () => {
  if (time.value > 0) return
  //先验证手机号格式合法性
  const result = await validateMobile()
  // console.log(result);
  if (!result.valid) {
    // 自动让手机号输入框 获取焦点
    mobileref.value?.focus()
    return
  }

  // console.log('验证码发出');
  // try {
  user.getCode(mobile.value)
  Message.success('获取验证码成功')
  // } catch (error) {
  //   Message.error('手机号不存在')
  // }

  //倒计时处理
  // count.value = 5
  // timeid = window.setInterval(() => {
  //   count.value--
  //   if (count.value <= 0) {
  //     clearTimeout(timeid)
  //   }
  // }, 1000);
  //点击发送按钮开始定时器
  // resume()
  start(5)
}


</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a href="javascript:;" v-if="activeName === 'mobile'" @click="activeName = 'account'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" @click="activeName = 'mobile'" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">

      <template v-if="activeName === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" v-model="account" placeholder="请输入用户名或手机号" />
          </div>
          <div class="error" v-if="accountErrorMessage"><i class="iconfont icon-warning" />{{ accountErrorMessage }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input type="password" v-model="password" placeholder="请输入密码" />
          </div>
          <div class="error" v-if="passwordErrorMessage"><i class="iconfont icon-warning" />{{ passwordErrorMessage }}
          </div>
        </div>
      </template>

      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" v-model="mobile" ref="mobileref" placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="mobileErrorMessage"><i class="iconfont icon-warning" />{{ mobileErrorMessage }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="password" v-model="code" placeholder="请输入验证码" />
            <span class="code" @click="send" :class="{ not: time > 0 }">{{ time > 0 ? `重新发送(${time})` : '发送验证码'
            }}</span>
          </div>
          <div class="error" v-if="codeErrorMessage"><i class="iconfont icon-warning" />{{ codeErrorMessage }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeErrorMessage"><i class="iconfont icon-warning" />{{ isAgreeErrorMessage }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="handleLogin">登录</a>
    </div>
    <div class="action">
      <!-- <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="" /> -->
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"><img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="QQ登录" border="0" /></a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.not {
  cursor: not-allowed !important;
}

// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: @xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 40px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: @priceColor;
          }

          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    img {
      cursor: pointer;
    }

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
